package com.dingup.paike.service.message.impl;

import com.alibaba.fastjson.JSON;
import com.dingup.api.Util.DateUtil;
import com.dingup.api.enums.ThirdPartyTypeEnum;
import com.dingup.api.model.classInfo.ClassInfo;
import com.dingup.api.template.message.bean.WxTemplateBean;
import com.dingup.paike.dao.PkLessonInfoMapper;
import com.dingup.paike.dao.PkLessonUserMapper;
import com.dingup.paike.dao.PkMessageDetailsMapper;
import com.dingup.paike.enums.MessageTypeEnum;
import com.dingup.paike.enums.MessageUserIdentityEnum;
import com.dingup.paike.feign.client.classInfo.ClassInfoFeignClient;
import com.dingup.paike.feign.client.user.UserFeignClient;
import com.dingup.paike.model.feedback.SendMsg;
import com.dingup.paike.model.message.PkMessageDetails;
import com.dingup.paike.model.pk.PkLessonInfo;
import com.dingup.paike.model.pk.PkLessonStudentSign;
import com.dingup.paike.service.message.WxMsgService;
import com.dingup.paike.util.ConstUtil;
import com.dingup.util.GDateUtil;
import com.suyeer.basic.util.BDateUtil;
import com.suyeer.basic.util.BLogUtil;
import com.suyeer.basic.util.BasicUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.dingup.api.template.message.util.WxMsgUtil.sendMsg;

/**
 * @author jun
 * @date 2018/10/19
 */
@Service
public class WxMsgServiceImpl implements WxMsgService {


    private static final String WX_TEMPLATE_FEEDBACK = "JFHQEXR8JcE0MDm7nCgYuTLyJuepQmcM9zg-1a-EdKo";
    private static final String MSG_OF_NEXT_DAY_LESSON_INFO = "%s/student/notice/%s/%s";
    private static final String MSG_OF_NEXT_DAY_LESSON_INFO_FOR_PARENTS = "%s/parents/notice/%s/%s";
    private static final String MSG_OF_CLASS_IN_LESSON_INFO = "%s/student/going/%s";
    private static Logger logger = LoggerFactory.getLogger(WxMsgServiceImpl.class);
    @Autowired
    PkMessageDetailsMapper pkMessageDetailsMapper;
    @Autowired
    PkLessonInfoMapper pkLessonInfoMapper;
    @Autowired
    PkLessonUserMapper pkLessonUserMapper;
    @Autowired
    UserFeignClient userFeignClient;
    @Autowired
    ClassInfoFeignClient classInfoFeignClient;

    /**
     * 提前 20 分钟给学生发送上课提醒
     * @param lessonName
     * @param pkLessonId
     * @param openId
     * @param beginTime
     * @param userId
     * @param userName
     */
    @Override
    @Async
    public void sendMsgAt20MinBeforeClass(String lessonName, Integer pkLessonId, String openId, Date beginTime, String userId, String userName, MessageTypeEnum type) {
        String url = String.format(MSG_OF_CLASS_IN_LESSON_INFO, ConstUtil.SYS_CONFIG_DATA.getOpenDomainName(), pkLessonId);
        String timeContent = null;
        if (MessageTypeEnum.MESSAGE_CLASS_BEFORE_ONE_HOUR.equals(type)) {
            timeContent = "1小时";
        } else if (MessageTypeEnum.MESSAGE_CLASS_CLASS_IN.equals(type)) {
            timeContent = "20min";
        }
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl(url);
        fwTemplateBean.setTemplate_id("LXgdpp2JM_HP67RuDaJyY9Sx5idIe5TzYDp7pLsrlBQ");
        fwTemplateBean.setTouser(openId);
        fwTemplateBean.addItem("first", "还有" + timeContent + "就要上课啦,快进入教室吧", "#4e72b8");
        fwTemplateBean.addItem("keyword1", lessonName, "#4e72b8");
        fwTemplateBean.addItem("keyword2", BDateUtil.getDateStr(beginTime), "#4e72b8");
        fwTemplateBean.addItem("remark", "为了保证上课质量，请在上课前退出杀毒和各类电脑卫士软件，插上网线或者选择一个靠近路由器" +
                "的地方，打开房间灯，插上耳机和麦克风，提前进入教室检测设备。", "#4e72b8");
        String pkMessageDetailsId = BasicUtil.getUUID();
        PkMessageDetails pkMessageDetails = getPkMessageDetails(userId, userName, openId);
        try {
            sendMsg(fwTemplateBean);
            pkMessageDetails.setIfSendSuccess(true);
        } catch (Exception e) {
            pkMessageDetails.setIfSendSuccess(false);
            BLogUtil.error("发送课程提醒失败, 课程名称: {}, 用户openId: {}", lessonName, openId);
        }
        pkMessageDetails.setPkLessonId("[" + pkLessonId + "]");
        pkMessageDetails.setId(pkMessageDetailsId);
        pkMessageDetails.setMessageContent("还有" + timeContent + "就要上课啦,快进入教室吧");
        pkMessageDetails.setMessageUrl(url);
        pkMessageDetails.setMessageType(type);
        pkMessageDetailsMapper.insertSelective(pkMessageDetails);
    }

    /**
     * 给学生发送第二天课节提醒
     *
     * @param openId
     * @param date
     * @param userName
     * @param userId
     */
    @Override
    @Async
    public void sendMsgOfNextDayLessonInfo(String openId, Date date, String userName, String userId,
                                           List<Integer> pkLessonIds) {

        String pkMessageDetailsId = BasicUtil.getUUID();
        String url = String.format(MSG_OF_NEXT_DAY_LESSON_INFO, ConstUtil.SYS_CONFIG_DATA.getOpenDomainName(), userId, pkMessageDetailsId);
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl(url);
        fwTemplateBean.setTemplate_id("4oG9qtLNLPn92ew8rMqditnksAlkdTdEIOdbl3NVq0M");
        fwTemplateBean.setTouser(openId);
        fwTemplateBean.addItem("first", userName + "明天有课要上", "#4e72b8");
        fwTemplateBean.addItem("keyword1", "明日课程", "#4e72b8");
        fwTemplateBean.addItem("keyword2", GDateUtil.getShortDateStr(date), "#4e72b8");
        fwTemplateBean.addItem("remark", "请点击详情查看明日课表, 并点击确认收到!", "#4e72b8");
        PkMessageDetails pkMessageDetails = getPkMessageDetails(userId, userName, openId);
        try {
            sendMsg(fwTemplateBean);
            pkMessageDetails.setIfSendSuccess(true);
        } catch (Exception e) {
            pkMessageDetails.setIfSendSuccess(false);
            BLogUtil.error("发送第二天的课程提醒失败, 用户姓名: {}, 用户Id: {}", userName, userId);
        }
        String ids = pkLessonIds.stream().map(String::valueOf).collect(Collectors.joining("],[", "[", "]"));
        pkMessageDetails.setPkLessonId(ids);
        pkMessageDetails.setId(pkMessageDetailsId);
        pkMessageDetails.setMessageContent("上课提醒:" + "明日课程");
        pkMessageDetails.setMessageUrl(url);
        pkMessageDetails.setMessageType(MessageTypeEnum.MESSAGE_CLASS_INFLATED);
        pkMessageDetailsMapper.insertSelective(pkMessageDetails);
    }

    @Override
    @Async
    public void sendMsgOfNextDayLessonInfoForParents(String openId, Date date, String userName, String userId, List<Integer> pkLessonIds) {
        String pkMessageDetailsId = BasicUtil.getUUID();
        String url = String.format(MSG_OF_NEXT_DAY_LESSON_INFO_FOR_PARENTS, ConstUtil.SYS_CONFIG_DATA.getOpenDomainName(), userId, pkMessageDetailsId);
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl(url);
        fwTemplateBean.setTemplate_id("4oG9qtLNLPn92ew8rMqditnksAlkdTdEIOdbl3NVq0M");
        fwTemplateBean.setTouser(openId);
        fwTemplateBean.addItem("first", userName + "明天有课要上", "#4e72b8");
        fwTemplateBean.addItem("keyword1", "明日课程", "#4e72b8");
        fwTemplateBean.addItem("keyword2", GDateUtil.getShortDateStr(date), "#4e72b8");
        fwTemplateBean.addItem("remark", "请点击详情查看" + userName + "同学的明日课表", "#4e72b8");
        PkMessageDetails pkMessageDetails = getPkMessageDetails(userId, userName + "-家长", openId);
        try {
            sendMsg(fwTemplateBean);
            pkMessageDetails.setIfSendSuccess(true);
        } catch (Exception e) {
            pkMessageDetails.setIfSendSuccess(false);
            BLogUtil.error("发送家长明日课程提醒失败, 用户姓名: {}, 用户Id: {}", userName, userId);
        }
        pkMessageDetails.setId(pkMessageDetailsId);
        pkMessageDetails.setMessageContent("请点击详情查看" + userName + "同学的明日课表");
        pkMessageDetails.setMessageUrl(url);
        pkMessageDetails.setMessageType(MessageTypeEnum.MESSAGE_CLASS_INFLATED);
        pkMessageDetailsMapper.insertSelective(pkMessageDetails);
    }

    /**
     * 开课5分钟后发送课程出勤情况
     *
     * @param openId
     * @param url
     * @param className
     * @param lessonName
     * @param lessonTime
     * @param attendanceInfo
     */
    @Override
    @Async
    public void sendCountAbsentUserMsg(String openId, String url, String className,
                                       String lessonName, String lessonTime, String attendanceInfo) {
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl(url);
        fwTemplateBean.setTemplate_id("MkEwcUQiyvBolrRkvVd5PT0i8Mj0S7GkRJ2L4FOqYOU");
        fwTemplateBean.setTouser(openId);
        fwTemplateBean.addItem("first", className, "#4e72b8");
        fwTemplateBean.addItem("keyword1", lessonName, "#4e72b8");
        fwTemplateBean.addItem("keyword2", lessonTime, "#4e72b8");
        fwTemplateBean.addItem("keyword3", attendanceInfo, "#4e72b8");
        fwTemplateBean.addItem("remark", "", "#4e72b8");
        try {
            sendMsg(fwTemplateBean);
        } catch (Exception e) {
            BLogUtil.error("发送开课5分钟后发送课程出勤情况信息失败, 用户openId: " + openId);
        }
    }
    @Override
    public Boolean sendFeedBackMsg(SendMsg sendMsg) {
        if (StringUtils.isBlank(sendMsg.getOpenId())) {
            logger.error("发送课程反馈失败,openid为空, 课程: " + sendMsg.getKeyword2() + " 发送json: " + JSON.toJSONString(sendMsg));
            return true;
        }
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl(sendMsg.getUrl());
        fwTemplateBean.setTemplate_id(WX_TEMPLATE_FEEDBACK);
        fwTemplateBean.setTouser(sendMsg.getOpenId());
        fwTemplateBean.addItem("first", sendMsg.getFirst(), sendMsg.getColor());
        fwTemplateBean.addItem("keyword1", sendMsg.getKeyword1(), sendMsg.getColor());
        fwTemplateBean.addItem("keyword2", sendMsg.getKeyword2(), sendMsg.getColor());
        fwTemplateBean.addItem("keyword3", sendMsg.getKeyword3(), sendMsg.getColor());
        fwTemplateBean.addItem("remark", sendMsg.getRemark(), sendMsg.getColor());
        Boolean ifSend = false;
        String res = null;
        try {
            sendMsg(fwTemplateBean);
            ifSend = true;
        } catch (Exception e) {
            ifSend = false;
            e.printStackTrace();
        }
        return ifSend;
    }

    @Override
    @Async
    public void sendParentWxMsgForStudentSign(PkLessonStudentSign sign) {
        List<String> parentOpenIds = userFeignClient.getParentWxOpenId(sign.getUserId());
        PkLessonInfo pkLessonInfo = pkLessonInfoMapper.selectByPrimaryKey(sign.getPkLessonId());
        String studentName = userFeignClient.getUserNameByUserId(sign.getUserId());
        String attendanceInfo = studentName + "已到校";
        ClassInfo classInfo = classInfoFeignClient.getSimpleClassInfo(pkLessonInfo.getClassId());
        if (!CollectionUtils.isEmpty(parentOpenIds)) {
            parentOpenIds.forEach(
                    parentOpenId -> sendCountAbsentUserMsg(parentOpenId,
                            "",
                            classInfo.getClassName(),
                            pkLessonInfo.getLessonName(),
                            DateUtil.getDTS(pkLessonInfo.getBeginTime()) + "-" + DateUtil.getOnlyTimeFormatStr(pkLessonInfo.getEndTime()),
                            attendanceInfo)
            );
        }
    }

    @Override
    @Async
    public void sendMsgForStudentFinishHomework(String openId, String userId, String userName, String homeworkName, Date expiredTime) {
        String pkMessageDetailsId = BasicUtil.getUUID();
        String url = "";
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl(url);
        fwTemplateBean.setTemplate_id("BIQKxgFU7GTh_QcU7e6Q6eEWSTq-EAJm8pr1ZbXoVYk");
        fwTemplateBean.setTouser(openId);
        fwTemplateBean.addItem("first", "你有一份作业需要填写", "#4e72b8");
        fwTemplateBean.addItem("keyword1", "", "#4e72b8");
        fwTemplateBean.addItem("keyword2", homeworkName, "#4e72b8");
        fwTemplateBean.addItem("keyword3", DateUtil.date2Str(expiredTime), "#4e72b8");
        fwTemplateBean.addItem("remark", "", "#4e72b8");
        PkMessageDetails pkMessageDetails = getPkMessageDetails(userId, userName, openId);
        try {
            sendMsg(fwTemplateBean);
            pkMessageDetails.setIfSendSuccess(true);
        } catch (Exception e) {
            pkMessageDetails.setIfSendSuccess(false);
            BLogUtil.error("学生的作业消息提醒失败, 用户openId: " + openId);
        }
        pkMessageDetails.setId(pkMessageDetailsId);
        pkMessageDetails.setMessageContent("作业提醒:" + homeworkName);
        pkMessageDetails.setMessageUrl(url);
        pkMessageDetails.setMessageType(MessageTypeEnum.MESSAGE_HOMEWORK_FINISH_STUDENT);
        pkMessageDetailsMapper.insertSelective(pkMessageDetails);
    }

    private PkMessageDetails getPkMessageDetails(String userId, String userName, String openId) {
        PkMessageDetails pkMessageDetails = new PkMessageDetails();
        Date currentDate = new Date();
        pkMessageDetails.setUserId(userId);
        pkMessageDetails.setThirdPartyId(openId);
        pkMessageDetails.setThirdPartyType(ThirdPartyTypeEnum.WEI_XIN);
        pkMessageDetails.setUserIdentity(MessageUserIdentityEnum.STUDENT);
        pkMessageDetails.setUserName(userName);
        pkMessageDetails.setIfReceiveConfirm(false);
        pkMessageDetails.setCreateTime(currentDate);
        pkMessageDetails.setIfReceiveConfirm(false);
        pkMessageDetails.setIfSendSuccess(false);
        return pkMessageDetails;
    }
}
